package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.TestMapper;
import com.tanhua.common.mapper.TestResultMapper;
import com.tanhua.common.pojo.*;
import com.tanhua.common.pojo.TestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class SoulTestService {

    @Autowired
    private TestMapper testMapper;
    @Autowired
    private TestResultMapper testResultMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    private static final String ISLOCK_REDIS_KEY_PREFIX = "ISLOCK_";
    private static final String REPORT_REDIS_KEY_PREFIX = "REPORT_";
    private static final String TEST_REDIS_KEY_PREFIX = "TEST_USER_";



    public List<Test> queryTest() {
        User user = UserThreadLocal.get();
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }

        String redisKey=TEST_REDIS_KEY_PREFIX+Convert.toStr(user.getId());
        redisTemplate.opsForHash().put(redisKey,ISLOCK_REDIS_KEY_PREFIX+"1","0");
        //查询试卷集合
        List<Test> testList = testMapper.selectList(new QueryWrapper<>());
        //遍历试卷
        for (Test test : testList) {
            List<TestQuestion> questionList = testMapper.queryQuestionsById(test.getId());
            for (TestQuestion testQuestion : questionList) {
                String id = testQuestion.getId();
                testQuestion.setId(test.getId() + ":" + id);
            }
            //遍历问题 向问题中注入答案
            for (TestQuestion question : questionList) {
                String[] strings = question.getId().split(":");
                String optionJson = testMapper.queryOptionByQuestionId(strings[1]);
                //解析答案json 注入问题当中
                List<Option> options = JSONUtil.toList(optionJson, Option.class);
                question.setOptions(options);
            }
            //向试卷中注入问题
            test.setQuestions(questionList);


            String reportRedisKey=REPORT_REDIS_KEY_PREFIX+test.getId();
            String isLockRedisKey=ISLOCK_REDIS_KEY_PREFIX+test.getId();
            if(redisTemplate.opsForHash().hasKey(redisKey,reportRedisKey)){
                test.setReportId((String) redisTemplate.opsForHash().get(redisKey,reportRedisKey));
            }


            if(redisTemplate.opsForHash().hasKey(redisKey,isLockRedisKey)){
                Integer islock = Convert.toInt(redisTemplate.opsForHash().get(redisKey, isLockRedisKey));
                test.setIsLock(islock);
            }else{
                test.setIsLock(1);
            }
        }
        return testList;
    }


    public String submitTest(String json) {
        User user = UserThreadLocal.get();

        JSONObject jsonObject = JSONUtil.parseObj(json);
        List answers = jsonObject.get("answers", List.class);
        List<TestQuestion> testQuestions = new ArrayList<>();
        int totalScore = 0;
        String testId=null;
        for (Object answer : answers) {
            JSONObject obj = JSONUtil.parseObj(answer);
            String testIdAndQuestionId = Convert.toStr(obj.get("questionId"));
            String[] strings = testIdAndQuestionId.split(":");
            Integer questionId = Convert.toInt(strings[1]);
            String optionId = Convert.toStr(obj.get("optionId"));
            int score = testResultMapper.findScoreByQuestionIdAndOptionId(questionId, optionId);
            totalScore += score;
            //testid赋值
            testId=strings[0];
        }
        String redisKey=TEST_REDIS_KEY_PREFIX+Convert.toStr(user.getId());
        String reportRedisKey=REPORT_REDIS_KEY_PREFIX+testId;
        //下一级试题解锁
        String isLockredisKey=ISLOCK_REDIS_KEY_PREFIX+(Convert.toInt(testId)+1);
        redisTemplate.opsForHash().put(redisKey,isLockredisKey,"0");
        //判断分数所在区间 返回相应类型结果
        if (totalScore > 0 && totalScore <= 21) {
            //reportId存入redis
            redisTemplate.opsForHash().put(redisKey,reportRedisKey,"1");
            //保存用户画像
            testResultMapper.saveUserAndResult(user.getId(), "1");
            return "1";
        } else if (totalScore > 21 && totalScore <= 40) {
            redisTemplate.opsForHash().put(redisKey,reportRedisKey,"2");
            testResultMapper.saveUserAndResult(user.getId(), "2");
            return "2";
        } else if (totalScore > 40 && totalScore <= 55) {
            redisTemplate.opsForHash().put(redisKey,reportRedisKey,"3");
            testResultMapper.saveUserAndResult(user.getId(), "3");
            return "3";
        } else if (totalScore > 55) {
            redisTemplate.opsForHash().put(redisKey,reportRedisKey,"4");
            testResultMapper.saveUserAndResult(user.getId(), "4");
            return "4";
        }
        return null;
    }


    public TestResult queryResult(String id) {
        User user = UserThreadLocal.get();
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }

        QueryWrapper<TestResult> queryWrapper = new QueryWrapper<TestResult>().eq("id", id);
        TestResult testResult = testResultMapper.selectOne(queryWrapper);
        //生成随机维度
        Dimension dimension1 = new Dimension("外向", Convert.toStr(RandomUtil.randomInt(100) + 1) + "%");
        Dimension dimension2 = new Dimension("判断", Convert.toStr(RandomUtil.randomInt(100) + 1) + "%");
        Dimension dimension3 = new Dimension("理性", Convert.toStr(RandomUtil.randomInt(100) + 1) + "%");
        Dimension dimension4 = new Dimension("精神小伙", Convert.toStr(RandomUtil.randomInt(100) + 1) + "%");
        ArrayList<Dimension> dimensions = new ArrayList<>();
        dimensions.add(dimension1);
        dimensions.add(dimension2);
        dimensions.add(dimension3);
        dimensions.add(dimension4);
        testResult.setDimensions(dimensions);
        // 查找相似的人

        List<Object> similarIdList = testResultMapper.findSimilar(id);
        if(CollUtil.isEmpty(similarIdList)){
            return testResult;
        }
        List<UserInfo> list = userInfoService.queryUserInfoByUserIdList(similarIdList);
        ArrayList<SimilarYou> similarYous = new ArrayList<>();
        //排除自己
        for (UserInfo userInfo : list) {
            if (userInfo.getUserId() == user.getId()) {
                continue;
            }
            SimilarYou similarYou = new SimilarYou(Convert.toInt(userInfo.getId()), userInfo.getLogo());
            similarYous.add(similarYou);
        }
        testResult.setSimilarYou(similarYous);
        return testResult;
    }
}
